package com.yuxin.tongyi.lsll.sub;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.common.TongyiTeaApplication;
import com.yuxin.tongyi.lsll.pojo.ClassObj;
import com.yuxin.tongyi.lsll.pojo.LifeInfo;
import com.yuxin.tongyi.lsll.pojo.LifeInfoList;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.pojo.Student;
import com.yuxin.tongyi.lsll.pojo.StudentInfo;
import com.yuxin.tongyi.lsll.select.SelectClassActivity;
import com.yuxin.tongyi.lsll.thread.GetClassFirstThread;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;

public class DayLifeActivity extends BaseActivity {
	private static final String TAG = "DayLifeActivity";

	private Button btnSend, btnPreview, btnBack;

	private String CurrClassID; // 当前选择项
	private String CurrentClassName;
	private GetClassFirstThread mClassThread; //班级列表线程
	private String CurrGradeID;  // 当前年级
	private TextView tvClass;

	private ListView lvStudentList; // 学生列表
	private SimpleAdapter stuAdapter;
	private StudentThread mStudentThread;  //学生列表线程
	private String CurrentStuID;    //当前学生
	private StudentInfo studentInfolist;     //学生信息list实体类
	private List<Map<String, Object>> studentlist;
	private String[] from;
	private int[] to;

	private DayLifeThread mDayLifeThread; //一日生活线程
	//private LifeInfoList lifeInfoList;       //一日生活list实体类
	private ArrayList<LifeInfo> daylifeList; //一日生活列表
	private String jsonStr;
	private boolean Flag; //是否已经保存一日生活  false:未保存 ture:已保存
	//private ArrayList<String> daylifeDefault;   //一日生活默认值 

	private TextView tvDate; // 当前日期
	private MyHandler mHandler;
	private LoginInfo loginInfo;
	private HttpRequestUtil request;
	
//	private static final String Class_Info = "ClassInfo";
	private static final String Student_Info = "StudentInfo";
	private static final String Daylife_Info = "DaylifeInfo";

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub_daylife);

		PubUtil.showProgressDialog(DayLifeActivity.this, Constants.MSG_LOADING, Constants.MSG_WAIT);
		initView();
		initData();

		request = new HttpRequestUtil();
		mHandler = new MyHandler();
		mClassThread = new GetClassFirstThread(this, mHandler);
		mStudentThread = new StudentThread();
		studentlist = new ArrayList<Map<String, Object>>();
		daylifeList = new ArrayList<LifeInfo>();
		
		//lifeInfoList = new LifeInfoList();
		studentInfolist = new StudentInfo();

		new Thread(mClassThread).start();
	}

	public void initView() {
		tvDate = (TextView) findViewById(R.id.sub_daylife_tvDate);
		
		tvClass = (TextView) findViewById(R.id.sub_daylife_tvClassName);
		tvClass.setOnClickListener(new onClassClick());

		btnSend = (Button) findViewById(R.id.sub_daylife_btnSend);
		btnPreview = (Button) findViewById(R.id.sub_daylife_btnPreview);
		btnBack = (Button) findViewById(R.id.sub_daylife_btnBack);
		btnSend.setOnClickListener(new onBtnClickListener());
		btnPreview.setOnClickListener(new onBtnClickListener());
		btnBack.setOnClickListener(new onBtnClickListener());
		lvStudentList = (ListView) findViewById(R.id.sub_daylife_lvStudent);
		from = new String[] { "stuid", "stuname", "btnedit" };
		to = new int[] { R.id.sub_daylife_tvStuId, R.id.sub_daylife_tvStuName, R.id.sub_daylife_imageEdit };
		lvStudentList.setOnItemClickListener(new onItemClickListener());
	}
	
	class onClassClick implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent();
			intent.setClass(DayLifeActivity.this, SelectClassActivity.class);
			startActivityForResult(intent, Constants.REQUEST_CODE_ClASS);
		}
	}

	public void initData() {
		try {
			loginInfo = (LoginInfo) TongyiTeaApplication.getMap().get(Constants.GLOBAL_LOGININFO);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		tvDate.setText(dateStr);

		//默认值
		//daylifeDefault = getDefaultData();
	}

	private class onBtnClickListener implements OnClickListener {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			//发送
			case R.id.sub_daylife_btnSend:
				if(lvStudentList.getCount()==0) {
					PubUtil.showToast(DayLifeActivity.this, "暂无学生信息");	
					return;
				}
				
				PubUtil.showProgressDialog(DayLifeActivity.this, Constants.MSG_SENDING, Constants.MSG_WAIT);
				
				
				jsonStr = GetJsonDataToString((ArrayList<LifeInfo>) TongyiTeaApplication.getMap().get(Constants.GLOBAL_LIST_DAYLIFE));
				//Log.i(TAG, daylifeList.size() + "--------11----------");
				
				mDayLifeThread = new DayLifeThread("S");
				new Thread(mDayLifeThread).start();
				
				break;
			//预览
			case R.id.sub_daylife_btnPreview:
				if(lvStudentList.getCount()==0) {
					PubUtil.showToast(DayLifeActivity.this, "暂无学生信息");	
					return;
				}
				Intent intent = new Intent(DayLifeActivity.this, DayLifePreviewActivity.class);
				Bundle bundle = new Bundle();
				//bundle.putSerializable("lifeInfoList", lifeInfoList);  //班级一日生活信息
				//bundle.putSerializable("studentlist", studentInfolist);  //班级学生列表 
				bundle.putString("classname", CurrentClassName);
				bundle.putString("date", tvDate.getText().toString()); // 当前日期
				bundle.putString("gradeid", CurrGradeID);   //年级
				bundle.putString("classid", CurrClassID);
				intent.putExtras(bundle);

				startActivity(intent);
				break;
			//返回
			case R.id.sub_daylife_btnBack:
				DayLifeActivity.this.finish();
				break;
			}
		}
	}

	private class onItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			String name = ((TextView) view.findViewById(R.id.sub_daylife_tvStuName)).getText().toString();
			CurrentStuID = ((TextView) view.findViewById(R.id.sub_daylife_tvStuId)).getText().toString();
			// showToast( "position:"+position + " id:" + id + " " + name);
			Intent intent = new Intent(DayLifeActivity.this, DayLifeDetailActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("id", CurrentStuID);
			bundle.putString("name", name); // 选中宝宝
			bundle.putString("date", tvDate.getText().toString()); // 当前日期
			bundle.putString("gradeid", CurrGradeID);   //年级
			//传值
			daylifeList = (ArrayList<LifeInfo>)TongyiTeaApplication.getMap().get(Constants.GLOBAL_LIST_DAYLIFE);
			for(LifeInfo info: daylifeList){
				if(info.getStudentId().equals(CurrentStuID) ){
					bundle.putSerializable("lifeinfo", info);
					break;
				}
			}
			intent.putExtras(bundle);
			startActivityForResult(intent, Constants.REQUEST_CODE_DAYLIFE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constants.REQUEST_CODE_DAYLIFE:
			if (resultCode == Activity.RESULT_OK) {
				// 更新list
				Bundle b = data.getExtras();
				if(b != null){
					LifeInfo backinfo = (LifeInfo) b.getSerializable("lifeinfo");
					
					daylifeList = (ArrayList<LifeInfo>)TongyiTeaApplication.getMap().get(Constants.GLOBAL_LIST_DAYLIFE);
					for(LifeInfo info: daylifeList){
						if(backinfo.getStudentId().equals(info.getStudentId())){
							daylifeList.remove(info);
							daylifeList.add(backinfo);
							TongyiTeaApplication.getMap().put(Constants.GLOBAL_LIST_DAYLIFE, daylifeList);
							break;
						}
					}
				}
			}
			break;
		case Constants.REQUEST_CODE_ClASS:
			if (resultCode == Activity.RESULT_OK) {
				Bundle b = data.getExtras();
				if(b != null){
					String SelectClassId = b.getString(Constants.SELECT_CLASS_ID);
					CurrentClassName = b.getString(Constants.SELECT_CLASS_NAME);
					if(!SelectClassId.equals(CurrClassID)){
						CurrClassID = SelectClassId;
						tvClass.setText(CurrentClassName);
						PubUtil.showProgressDialog(DayLifeActivity.this, Constants.MSG_LOADING, Constants.MSG_WAIT);
						getStudentListByClassId(CurrClassID);
					}
				}
			}
			break;
		}
	}

	private void setClassData(ClassObj info) {
		CurrClassID = info.getClassId();
		CurrentClassName = info.getClassName();
		CurrGradeID = info.getGradeId();
		
		tvClass.setText(CurrentClassName);
	}
	
	private void setStudentData(StudentInfo info) {
		List<Student> list = info.getStudent();
		studentlist.clear();
		for (Student obj : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("stuid", obj.getStudentId());
			map.put("stuname", obj.getStudentName());
			map.put("btnedit", R.drawable.edit);
			studentlist.add(map);
		}
		stuAdapter = new SimpleAdapter(this, studentlist, R.layout.sub_daylife_stulist, from, to);
		lvStudentList.setAdapter(stuAdapter);
		
		//保存学生列表到application中
		TongyiTeaApplication.getMap().put(Constants.GLOBAL_LIST_STUDENT, list);
		
	}
	
	/**
	 * 存入临时daylifeList数据
	 * @param hasData
	 */
	private void setLifeInfoData(boolean hasData, LifeInfoList lifeInfoList){
		daylifeList.clear();
		//服务器是否已经保存一日生活
		if(hasData){
			//有数据
			daylifeList = (ArrayList<LifeInfo>) lifeInfoList.getLifeInfo();
		}else{
			//无数据
			List<Student> list = studentInfolist.getStudent();
			ArrayList<String> defData = getDefaultData();
			int i=0;
			for(Student obj: list){
				LifeInfo info = new LifeInfo();
				info.setStudentId(obj.getStudentId());
				info.setStudentName(obj.getStudentName());
				info.setAttendence(defData.get(0));
				info.setFoodStatus(defData.get(1));
				info.setFoodCook(defData.get(2));
				info.setSleepStatus(defData.get(3));
				info.setHomeWork(defData.get(4));
				info.setEdcution(defData.get(5));
				info.setOpenair(defData.get(6));
				info.setGame(defData.get(7));
				info.setHealth(defData.get(8));
				info.setCourse(defData.get(9));
				info.setRemark(defData.get(10));
				info.setDriking(defData.get(11));
				info.setMotions(defData.get(12));
				
				daylifeList.add(info);
				i++;
			}
			//lifeInfoList.getLifeList().clear();
			//lifeInfoList.setLifeInfo(daylifeList);
		}
		TongyiTeaApplication.getMap().put(Constants.GLOBAL_LIST_DAYLIFE, daylifeList);
	}

	private class StudentThread implements Runnable {
		@Override
		public void run() {
			HttpRequestUtil request1 = new HttpRequestUtil();
			Boolean requestFlag = request1.babyListRequest(loginInfo.getLoginName(), loginInfo.getPassword(),
					CurrClassID);
			String status = request1.getStatus();
			Message msg = mHandler.obtainMessage();
			try {
				if (requestFlag) {
					if (status != null && !"".equals(status)) {
						Bundle mbundle = new Bundle();
						List<Object> list = request1.getObjList();
						if (list != null && list.size() > 0) {

							Object obj = list.get(0);
							if (obj instanceof StudentInfo) {
								StudentInfo info = (StudentInfo) obj;
								mbundle.putSerializable(Student_Info, info);
							}
							msg.what = Constants.TH_STUDENT_ON;
							msg.setData(mbundle);
						} else {
							msg.what = Constants.TH_NODATA;
						}
					} else {
						msg.what = Constants.TH_DATA_ERROR;
					}
				} else { // 访问服务器失败
					msg.what = Constants.TH_SERVER_OFF;
				}
				mHandler.sendMessage(msg);
			} catch (Exception e) {
				msg.what = Constants.TH_SERVER_OFF;
				mHandler.sendMessage(msg);
			}
		}

	}

	private class DayLifeThread implements Runnable {
		
		String tFlag;  // S: 发送一日生活   R: 接收一日生活信息
		public DayLifeThread(String Flag){
			this.tFlag = Flag;
		}
		
		@Override
		public void run() {
			boolean requestFlag = false;
			
			if(tFlag.equals("R")){
				requestFlag = request.requestDayLife(loginInfo.getLoginName(), loginInfo.getPassword(),
						tvDate.getText().toString(), null, CurrClassID);
			}else if(tFlag.equals("S")){
				requestFlag = request.requestSendDayLife(loginInfo.getLoginName(), loginInfo.getPassword(), CurrClassID, jsonStr);
			}
			
			String status = request.getStatus();
			Log.i(TAG, status + "  :status");
			Message msg = mHandler.obtainMessage();
			try {
				if (requestFlag) {
					if (status != null && !"".equals(status)) {
						if(tFlag.equals("R")){			
							List<Object> list = request.getObjList();
							if (list != null && list.size() > 0) {
								LifeInfoList LifeInfoBean = (LifeInfoList) list.get(0);
								Bundle b = new Bundle();
								b.putSerializable(Daylife_Info, LifeInfoBean);
								msg.what = Constants.TH_DAYLIFE;
								msg.setData(b);
							} else {
								msg.what = Constants.TH_DAYLIFE_NODATA;
							}
						}else if(tFlag.equals("S")){
							msg.what = Constants.TH_DAYLIFE_SEND;
						}
					} else {
						msg.what = Constants.TH_DATA_ERROR;
					}
				} else { // 访问服务器失败
					msg.what = Constants.TH_SERVER_OFF;
				}
				mHandler.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
				msg.what = Constants.TH_SERVER_OFF;
				mHandler.sendMessage(msg);
			}
		}
	}

	private class MyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle = msg.getData();
			switch (msg.what) {
			//读取首CLASS成功
			case Constants.TH_CLASS_ON:
				ClassObj classObj = (ClassObj) bundle.getSerializable(Constants.STREAM_CLASS_FIRST);
				setClassData(classObj);
				
				//获取相应班级的学生
				getStudentListByClassId(CurrClassID);
				break;
			//读取首CLASS失败，加载缓存
			case Constants.TH_CLASS_OFF:
				PubUtil.showToastLong(DayLifeActivity.this, Constants.MSG_READCACHE);	
				ClassObj classObj1 = (ClassObj) bundle.getSerializable(Constants.STREAM_CLASS_FIRST);
				setClassData(classObj1);
				
				//获取相应班级的学生
				getStudentListByClassId(CurrClassID);
				break;
			case Constants.TH_STUDENT_ON:
				studentInfolist = (StudentInfo) bundle.getSerializable(Student_Info);
				setStudentData(studentInfolist);
				if(studentlist.size()>0){
					mDayLifeThread = new DayLifeThread("R");
					new Thread(mDayLifeThread).start();
				}
				break;
			case Constants.TH_DAYLIFE:
				Flag = true;
				LifeInfoList lifeInfoList = (LifeInfoList) bundle.getSerializable(Daylife_Info);
				setLifeInfoData(Flag, lifeInfoList);
				PubUtil.closeProgressDialog();
				break;
			case Constants.TH_DAYLIFE_NODATA:
				Flag = false;
				setLifeInfoData(Flag, null);
				PubUtil.closeProgressDialog();
				break;
			case Constants.TH_DAYLIFE_SEND:
				PubUtil.closeProgressDialog();
				PubUtil.showDialog(DayLifeActivity.this, "提示","发送成功",null,false);		
				break;
			case Constants.TH_NODATA:
				lvStudentList.setAdapter(null);
				
				PubUtil.closeProgressDialog();
	        	PubUtil.showToast(DayLifeActivity.this, Constants.MSG_NODATA);		
				break;
			case Constants.TH_DATA_ERROR:
				PubUtil.closeProgressDialog();
	        	PubUtil.showToast(DayLifeActivity.this, Constants.MSG_DATA_ERROR);
				break;
			case Constants.TH_SERVER_OFF:
				PubUtil.closeProgressDialog();
	        	PubUtil.showToast(DayLifeActivity.this, Constants.MSG_SERVER_OFF);
				break;
			}
		}
	}

	private void getStudentListByClassId(String classid) {
		if (classid != null && !"".equals(classid)) {
			new Thread(mStudentThread).start();
		}
	}
	
	private ArrayList<String> getDefaultData(){
		ArrayList<String> list = new ArrayList<String>();
		list.add(getResources().getStringArray(R.array.attendence)[0]);
		list.add(getResources().getStringArray(R.array.foodStatus)[0]);
		list.add(getResources().getStringArray(R.array.foodCook)[0]);
		list.add(getResources().getStringArray(R.array.sleepStatus)[0]);
		list.add(getResources().getStringArray(R.array.homeWork)[0]);
		list.add(getResources().getStringArray(R.array.edcution)[0]);
		list.add(getResources().getStringArray(R.array.openair)[0]);
		list.add(getResources().getStringArray(R.array.game)[0]);
		list.add(getResources().getStringArray(R.array.health)[0]);
		list.add(getResources().getStringArray(R.array.course)[0]);
		//list.add(getResources().getStringArray(R.array.remark)[0]);
		list.add("");
		list.add(getResources().getStringArray(R.array.driking)[4]);
		list.add(getResources().getStringArray(R.array.motions)[0]);
		return list;
	}
	
	private String GetJsonDataToString(ArrayList<LifeInfo> list){
		Gson gson = new Gson();
		Type type = new TypeToken<List<LifeInfo>>(){}.getType();
		return gson.toJson(list, type);
		
	}
}
